/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-04-29
*/
package com.rzico.order.controller;

import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.*;
import com.rzico.basics.service.*;
import com.rzico.core.entity.SysBindUser;
import com.rzico.core.entity.SysEmployee;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.*;
import com.rzico.order.entity.Cart;
import com.rzico.order.entity.CartItem;
import com.rzico.order.entity.Order;
import com.rzico.order.entity.OrderItem;
import com.rzico.order.model.CartItemVo;
import com.rzico.order.service.CartItemService;
import com.rzico.order.service.CartService;
import com.rzico.order.service.OrderItemService;
import com.rzico.order.service.OrderService;
import com.rzico.util.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 扫一扫控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-04-29
 */
@Api(description = "扫一扫")
@RestController
@RequestMapping("/q")
public class ScanController extends BaseController {

    @Autowired  @Lazy
    private SysBindUserService sysBindUserService;

    @Autowired
    private QrcodeService qrcodeService;

    @Autowired
    private PromotionService promotionService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SysEmployeeService sysEmployeeService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private SysUserDataScopeService sysUserDataScopeService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private SysSequenceService sysSequenceService;

    /**
     * 扫一扫        签名:编码 + 32位MD5
     * 扫码核销       od+(订单编码)
     * 扫码绑定用户   uu+(用户id)
     * @return
     */

    @ApiOperation("扫一扫")
    @GetMapping("/scaner")
    public CommResult<Cart> scaner(String q) {

        if (q==null) {
            return CommResult.error("无效二维码");
        }

        Map<String,Object> data = new HashMap<>();

        // 绑定用户
        if (q.indexOf("user?id=")>=0) {
            SysUser sysUser = sysUserService.getCurrent();
            if (sysUser==null) {
                return CommResult.logout();
            }
            String uid = q.substring(q.length()-32);
            sysBindUserService.bindUser(sysUser.getId(),uid);
            return CommResult.success("绑定成功");

        } else
        // 扫码领券
        if (q.indexOf("/q/89")>=0) {

            SysUser sysUser = sysUserService.getCurrent();
            if (sysUser==null) {
                return CommResult.logout();
            }
            Qrcode qrcode = qrcodeService.findByQ(q);
            if (qrcode!=null) {
                if (qrcode.getStatus().equals(1)) {
                    return CommResult.error("已经使用");
                }
                Promotion promotion = promotionService.selectByPrimaryKey(qrcode.getPromotionId());
                if (promotion!=null) {
                    if (promotion.getGiftType().equals(0)) {
                        return CommResult.error("此功能未开通");
                    }
                    Member member = memberService.getCurrent();
                    if (promotion.getFirsted()!=null && promotion.getFirsted()==true) {
                        if (member.getAmount().compareTo(BigDecimal.ZERO)>0) {
                            return CommResult.error("新用户才能参与");
                        }
                    }
                    promotionService.createGift(promotion.getId(),member,sysSequenceService.generate("couponCode"));

                    qrcode.setStatus(1);
                    qrcode.setUsedDate(new Date());
                    qrcode.setMemberId(member.getId());
                    qrcodeService.updateByPrimaryKeySelective(qrcode);

                    return CommResult.success("领取成功");
                } else {
                    return CommResult.success("无效二维码");
                }

            } else {
                return CommResult.error("无效二维码");
            }

        } else
        // 扫码核销
        if (q.substring(0,2).equals("od")) {

            SysUser sysUser = sysUserService.getCurrent();
            if (sysUser==null) {
                return CommResult.logout();
            }

            String s = q.substring(2,q.length()-32);

            Order order = orderService.findBySn(s);

            order.setItemList(orderItemService.getItemList(order.getId()));

            String sign = q.substring(q.length()-32);
            if (!MD5Utils.getMD5Str("od"+s+order.getId()).toLowerCase().equals(sign.toLowerCase())) {
                return CommResult.success("无效二维码");
            }

            if (order.getShopId()==null) {
                return CommResult.error("不是到店提货订单");
            }

            try {
                Shop shop = shopService.selectByPrimaryKey(order.getShopId());
                if (shop.getSupplierId()==null) {
                    return CommResult.error("没有绑定供应商");
                }

                if (sysUser.getUserType().equals(1)) {

                   if (!sysUserDataScopeService.checkHasShopPermissio(sysUser.getId(),shop.getId())) {
                       return CommResult.error("您没有权限");
                   }

                } else {

                   Supplier supplier = supplierService.selectByPrimaryKey(shop.getSupplierId());
                   if (supplier==null) {
                       return CommResult.error("您没有权限");
                   }

                   if (!sysBindUserService.checkBindUser(sysUser.getId(),supplier.getUserId())) {
                       return CommResult.error("您没有权限");
                   }

                }

                orderService.scaner(order.getId(),sysSequenceService.generate("warehouse"));
                return CommResult.success("核销成功->"+order.getTitle());

            } catch (Exception e) {
                return CommResult.error(e.getMessage());
            }

        } else
        if (q.substring(0,4).toLowerCase().equals("http")) {
            data.put("url",q);
        }

        return CommResult.success(data);

    }


}
